$(document).ready(function() {
    $(document).ajaxStop(updateDom);
    $('body').removeClass('jsDisabled');
    if (window.location.hash) {
        var anchor = window.location.hash.replace("#", "");
        $('.accordion-body').addClass('collapse');
        $("#" + anchor + '.accordion-body').removeClass('collapse');
    }
    // initTooltip();
    $('#btn-feedback a').click(function() {
        showDialog('Feedback', this.href);
        return false;
    });
    if ($('#serverTime').length) {
        var initTime = new Date().getTime();
        $.ajax({
            url: '/ajax/time',
            success: function(server) {
                setTime(initTime, server.time);
            },
            global: false,
            dataType: 'json'
        });
    }
    updateDom();
});

function updateDom() {
    if (jQuery().combobox) {
        $('select.combobox').removeClass('combobox').combobox();
    }
    $('.js-hidden').hide();
    $('.js-collapse').removeClass('js-collapse').addClass('collapse');
    if (document.createElement("input").placeholder == undefined) {
        $('[placeholder]').focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        }).blur(function() {
            var input = $(this);
            if (input.val() == '' || input.val() == input.attr('placeholder')) {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }
        }).blur();
        $('[placeholder]').parents('form').submit(function() {
            $(this).find('[placeholder]').each(function() {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                }
            })
        });
    }
    $('[data-confirm]').each(function() {
        $(this).unbind('click.confirm').bind('click.confirm', function() {
            var confirmMessage = 'Are you sure you want to ' + $(this).attr('data-confirm') + '?';
            if (!confirm(confirmMessage)) {
                return false;
            }
            var appendUrl = $(this).attr('data-confirm-append');
            if (appendUrl) {
                $(this).attr('href', $(this).attr('href') + appendUrl);
            }
        });
    });
    $('form[data-validate-elements]').each(function() {
        var form = $(this);
        if (form.attr('data-validate-attached')) {
            return;
        }
        form.attr('data-validate-attached', 'attached');
        var formName = form.attr('name');
        if (!formName) {
            return;
        }
        var namespace = form.attr('data-validate-namespace');
        if (!namespace) {
            namespace = '';
        }
        var elements = form.attr('data-validate-elements').split(', ');
        if (!elements.length) {
            return;
        }
        elements = '[id=' + elements.join('], [id=') + ']';
        form.find(elements).blur(function() {
            var element = $(this);
            var fieldName = element.attr('id');
            var fieldValue = element.val();
            var controls = element.closest('.controls');
            var controlGroup = element.closest('.control-group');
            controls.find('ul.errors, .validation-message').remove();
            controls.append('<span class="validation-message"><i class="icon-spinner icon-spin text-info"></i></span>');
            $.post('/ajax/validate', {
                namespace: namespace,
                form: formName,
                field: fieldName,
                value: fieldValue
            }, function(result) {
                controls.find('.validation-message').remove();
                if (result.status !== 'success') {
                    return;
                }
                data = result.data;
                if (data.valid) {
                    controlGroup.removeClass('error').addClass('success');
                    controls.append('<span class="validation-message"><i class="icon-ok-sign text-success"></i></span>');
                } else {
                    controlGroup.removeClass('success').addClass('error');
                    controls.append('<ul class="errors"><li>' + data.errors.join('</li><li>') + '</li></ul>');
                }
                element.val(data.value);
            }, 'json');
        });
    });
}

function setTime(initTime, serverTime) {
    ellapsedTime = new Date().getTime() - initTime;
    $('#serverTime').html('Server time: <strong>' + new Date(serverTime + ellapsedTime).toUTCString().replace('GMT', 'UTC') + '</strong>');
    setTimeout('setTime(' + initTime + ',' + serverTime + ');', 500);
}

function showDialog(title) {
    $('#dlg-general').modal('show');
    $('#dlg-general-title').text(title);
    $('#dlg-general .modal-body').html('<div class="alert alert-info">Please wait...</div>');
    $('#dlg-general .modal-footer').html('');
}

function loadDialog(title, url) {
    $(document).ajaxStop(setDialogButtons);
    showDialog(title);
    $('#dlg-general .modal-body').load(url);
}

function setDialogButtons() {
    $(document).unbind('ajaxStop', setDialogButtons);
    var submitBtn = $('#dlg-general input[type=submit]');
    var submitVal = submitBtn.val();
    if (submitVal) {
        $('#dlg-general .form-actions').remove();
        $('#dlg-general .modal-footer').html('<a href="#" class="btn" data-dismiss="modal">Cancel</a> <button class="btn btn-primary" id="dlg-general-submit">' + submitVal + '</button>');
        $('#dlg-general-submit').click(function() {
            $('#dlg-general form').submit();
        });
        $('#dlg-general').keydown(function(event) {
            if (event.keyCode === 13) {
                $('#dlg-general form').submit();
                return false;
            }
        });
    }
}



! function(e) {
    "use strict";
    var t = function(t, n) {
        this.options = e.extend({}, e.fn.combobox.defaults, n);
        this.$source = e(t);
        this.$container = this.setup();
        this.$element = this.$container.find("input[type=text]");
        this.$target = this.$container.find("input[type=hidden]");
        this.$button = this.$container.find(".dropdown-toggle");
        this.$menu = e(this.options.menu).appendTo("body");
        this.matcher = this.options.matcher || this.matcher;
        this.sorter = this.options.sorter || this.sorter;
        this.highlighter = this.options.highlighter || this.highlighter;
        this.shown = false;
        this.selected = false;
        this.refresh();
        this.transferAttributes();
        this.listen()
    };
    t.prototype = e.extend({}, e.fn.typeahead.Constructor.prototype, {
        constructor: t,
        setup: function() {
            var t = e(this.options.template);
            this.$source.before(t);
            this.$source.hide();
            return t
        },
        parse: function() {
            var t = this,
                n = {},
                r = [],
                i = false;
            this.$source.find("option").each(function() {
                var s = e(this);
                if (s.val() === "") {
                    t.options.placeholder = s.text();
                    return
                }
                n[s.text()] = s.val();
                r.push(s.text());
                if (s.attr("selected")) i = s.text()
            });
            this.map = n;
            if (i) {
                this.$element.val(i);
                this.$container.addClass("combobox-selected");
                this.selected = true
            }
            return r
        },
        transferAttributes: function() {
            this.options.placeholder = this.$source.attr("data-placeholder") || this.options.placeholder;
            this.$element.attr("placeholder", this.options.placeholder);
            this.$target.prop("name", this.$source.prop("name"));
            this.$target.val(this.$source.val());
            this.$source.removeAttr("name");
            this.$element.attr("required", this.$source.attr("required"));
            this.$element.attr("rel", this.$source.attr("rel"));
            this.$element.attr("title", this.$source.attr("title"));
            this.$element.attr("class", this.$source.attr("class"));
            this.$element.attr("tabindex", this.$source.attr("tabindex"));
            this.$source.removeAttr("tabindex")
        },
        toggle: function() {
            if (this.$container.hasClass("combobox-selected")) {
                this.clearTarget();
                this.triggerChange();
                this.clearElement()
            } else {
                if (this.shown) {
                    this.hide()
                } else {
                    this.clearElement();
                    this.lookup()
                }
            }
        },
        clearElement: function() {
            this.$element.val("").focus()
        },
        clearTarget: function() {
            this.$source.val("");
            this.$target.val("");
            this.$container.removeClass("combobox-selected");
            this.selected = false
        },
        triggerChange: function() {
            this.$source.trigger("change")
        },
        refresh: function() {
            this.source = this.parse();
            this.options.items = this.source.length
        },
        select: function() {
            var e = this.$menu.find(".active").attr("data-value");
            this.$element.val(this.updater(e)).trigger("change");
            this.$source.val(this.map[e]).trigger("change");
            this.$target.val(this.map[e]).trigger("change");
            this.$container.addClass("combobox-selected");
            this.selected = true;
            return this.hide()
        },
        lookup: function(e) {
            this.query = this.$element.val();
            return this.process(this.source)
        },
        listen: function() {
            this.$element.on("focus", e.proxy(this.focus, this)).on("blur", e.proxy(this.blur, this)).on("keypress", e.proxy(this.keypress, this)).on("keyup", e.proxy(this.keyup, this));
            if (this.eventSupported("keydown")) {
                this.$element.on("keydown", e.proxy(this.keydown, this))
            }
            this.$menu.on("click", e.proxy(this.click, this)).on("mouseenter", "li", e.proxy(this.mouseenter, this)).on("mouseleave", "li", e.proxy(this.mouseleave, this));
            this.$button.on("click", e.proxy(this.toggle, this))
        },
        keyup: function(e) {
            switch (e.keyCode) {
                case 40:
                case 39:
                case 38:
                case 37:
                case 36:
                case 35:
                case 16:
                case 17:
                case 18:
                    break;
                case 9:
                case 13:
                    if (!this.shown) return;
                    this.select();
                    break;
                case 27:
                    if (!this.shown) return;
                    this.hide();
                    break;
                default:
                    this.clearTarget();
                    this.lookup()
            }
            e.stopPropagation();
            e.preventDefault()
        },
        blur: function(e) {
            var t = this;
            this.focused = false;
            var n = this.$element.val();
            if (!this.selected && n !== "") {
                this.$element.val("");
                this.$source.val("").trigger("change");
                this.$target.val("").trigger("change")
            }
            if (!this.mousedover && this.shown) setTimeout(function() {
                t.hide()
            }, 200)
        },
        mouseleave: function(e) {
            this.mousedover = false
        }
    });
    e.fn.combobox = function(n) {
        return this.each(function() {
            var r = e(this),
                i = r.data("combobox"),
                s = typeof n == "object" && n;
            if (!i) r.data("combobox", i = new t(this, s));
            if (typeof n == "string") i[n]()
        })
    };
    e.fn.combobox.defaults = {
        template: '<div class="combobox-container"><input type="hidden"><input type="text" autocomplete="off"><span class="add-on btn dropdown-toggle" data-dropdown="dropdown"><span class="caret"></span><span class="combobox-clear"><i class="icon-remove"></i></span></span></div>',
        menu: '<ul class="typeahead typeahead-long dropdown-menu"></ul>',
        item: '<li><a href="#"></a></li>'
    };
    e.fn.combobox.Constructor = t
}(window.jQuery)

function touchScroll(selector) {
    var isTouchDevice = function() {
        try {
            document.createEvent('TouchEvent');
            return true;
        } catch (e) {
            return false;
        }
    };
    if (isTouchDevice()) {
        var scrollStartPosY = 0;
        var scrollStartPosX = 0;
        $(selector).on("touchstart", function(e) {
            scrollStartPosY = this.scrollTop + e.originalEvent.touches[0].pageY;
            scrollStartPosX = this.scrollLeft + e.originalEvent.touches[0].pageX;
        });
        $(selector).on("touchmove", function(e) {
            if ((this.scrollTop < this.scrollHeight - this.offsetHeight && this.scrollTop + e.originalEvent.touches[0].pageY < scrollStartPosY - 5) || (this.scrollTop != 0 && this.scrollTop + e.originalEvent.touches[0].pageY > scrollStartPosY + 5))
                e.preventDefault();
            if ((this.scrollLeft < this.scrollWidth - this.offsetWidth && this.scrollLeft + e.originalEvent.touches[0].pageX < scrollStartPosX - 5) || (this.scrollLeft != 0 && this.scrollLeft + e.originalEvent.touches[0].pageX > scrollStartPosX + 5))
                e.preventDefault();
            this.scrollTop = scrollStartPosY - e.originalEvent.touches[0].pageY;
            this.scrollLeft = scrollStartPosX - e.originalEvent.touches[0].pageX;
        });
    }
}

function rand(max) {
    return Math.round(Math.random() * max);
}

function range(from, to, step) {
    if (step == undefined)
        step = 1;
    else
        step = parseInt(step);
    from = parseInt(from);
    to = parseInt(to);
    var result = [];
    for (var i = from; i <= to; i += step)
        result.push(i);
    return result;
}

function initControlPanel() {
    $('a[href^="/manage/cron/delete"]').click(function() {
        if (confirm('Are you sure you want to delete this cronjob?'))
            $('#contentText').load(this.href + '/confirm/yes');
        return false;
    });
    $('a[href^="/manage/cron/disable"]').click(function() {
        if (confirm('Are you sure you want to disable this cronjob?'))
            $('#contentText').load(this.href);
        return false;
    });
    $('a[href^="/manage/cron/run"]').click(function() {
        if (confirm('Are you sure you want to run this cronjob NOW?'))
            $('#contentText').load(this.href + '/confirm/yes');
        return false;
    });
    $('a[href^="/manage/group/delete"]').click(function() {
        if (confirm('Are you sure you want to delete this group?\nIts CronJobs will be moved to default group.'))
            $('#contentText').load(this.href + '/confirm/yes');
        return false;
    });
    $('a[href^="/manage/cron/enable"], a[href^="/manage/cron/order"], a[href^="/manage/cron/column"]').click(function() {
        $('#contentText').load(this.href);
        return false;
    });
    $('a[href^="/manage/group/edit"]').click(function() {
        loadDialog('Edit Group', this.href);
        return false;
    });
    $('a[href^="/manage/cron/logs"]').click(function() {
        $('#contentText').load(this.href);
        return false;
    });
    $('a[href^="/manage/cron/edit"], a[href^="/manage/cron/clone"]').click(function() {
        var thisRow;
        if (this.href.indexOf('id') === -1) {
            thisRow = $('#cronJobs tr:first');
        } else {
            thisRow = $(this).closest('tr');
        }
        var numOfVisibleCells = thisRow.children(':visible').length;
        $('#editingRow').remove();
        $('<tr id="editingRow"><td colspan="' + numOfVisibleCells + '"><h3>Edit CronJob</h3><div id="editingContents"><div class="alert alert-info">Please wait...</div></div></td></tr>').insertAfter(thisRow);
        $('#editingContents').load(this.href, function() {
            $('#editingContents .form-actions').prepend('<a href="#" class="btn" onclick="$(\'#editingRow\').remove(); return false;">Cancel</a>');
        });
        return false;
    });
    $('#cronJobs td:first').html('<input type="checkbox" id="checkAll">');
    $('.groupRow td:nth-child(2)').html('<input type="checkbox" class="groupCheckbox">');
    $('#checkAll').change(function() {
        var value = this.checked;
        $('input[name=ids\\[\\]], .groupCheckbox').each(function() {
            this.checked = value;
        });
    });
    $('.groupCheckbox').change(function() {
        var value = this.checked;
        $(this).parent().parent().nextUntil('.groupRow').find('input[name=ids\\[\\]]').each(function() {
            this.checked = value;
        });
    });
    var isCronSelected = function() {
        if (!$('input[name=ids\\[\\]]:checked').val()) {
            alert('Please select at least 1 cronjob!');
            return false;
        }
        return true;
    };
    $('label[for=batchDisableButton]').click(function() {
        if (!isCronSelected() || !confirm('Are you sure you want to disable selected cronjobs?')) {
            return false;
        }
    });
    $('label[for=batchRunButton]').click(function() {
        if (!isCronSelected() || !confirm('Are you sure you want to run selected cronjobs?')) {
            return false;
        }
    });
    $('label[for=batchDeleteButton]').click(function() {
        if (!isCronSelected() || !confirm('Are you sure you want to delete selected cronjobs?'))
            return false;
        $('#batchForm').attr('action', $('#batchForm').attr('action') + '/confirm/yes');
    });
    $('label[for=batchEnableButton]').click(function() {
        if (!isCronSelected())
            return false;
    });
    $('label[for=batchEditButton]').click(function() {
        if (!isCronSelected()) {
            return false;
        }
        var thisRow = $('#cronJobs tr:first');
        $('#editingRow').remove();
        var numOfVisibleCells = thisRow.children(':visible').length;
        $('<tr id="editingRow"><td colspan="' + numOfVisibleCells + '"><h3>Edit CronJobs</h3><div id="editingContents"><div class="alert alert-info">Please wait...</div></div></td></tr>').insertAfter(thisRow);
        var batchForm = $('#batchForm');
        $.post(batchForm.attr('action'), batchForm.serialize() + '&batchAction=edit', function(data) {
            $('#editingContents').html(data);
            $('#editingContents .form-actions').prepend('<a href="#" class="btn" onclick="$(\'#editingRow\').remove(); return false;">Cancel</a>');
        });
        return false;
    });
    $('#pointsBar').hover(function() {
        $('#cronJobs tr td:nth-child(7)').addClass('points');
    }, function() {
        $('#cronJobs tr td:nth-child(7)').removeClass('points');
    });
    // initTooltip();
}

function timeToInterval(minute, hour, day, month, weekday, second) {
    var step;
    var isAllWeekday = weekday.toString() == allWeekday.toString();
    var isAllMonth = month.toString() == allMonth.toString();
    var isAllDay = day.toString() == allDay.toString();
    var isAllHour = hour.toString() == allHour.toString();
    if (minute.indexOf('random') != -1) {
        minute = [0];
    }
    if (hour.indexOf('random') != -1) {
        hour = [0];
    }
    if (day.indexOf('L') != -1) {
        day = [0];
    }
    if (isAllWeekday && isAllMonth && isAllDay && isAllHour && minute.length === 60 && second.length === 2) {
        return 1;
    }
    if (isAllWeekday && isAllMonth && isAllDay && isAllHour && minute.length > 1) {
        step = minute[1] - minute[0];
        if (60 % step == 0 && minute[0] < step && minute.toString() == range(minute[0], 59, step).toString()) {
            var minuteSteps = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30];
            return 2 + minuteSteps.indexOf(step);
        }
    }
    if (isAllWeekday && isAllMonth && isAllDay && hour.length > 1 && minute.length == 1) {
        step = hour[1] - hour[0];
        if (24 % step == 0 && hour[0] < step && hour.toString() == range(hour[0], 23, step).toString()) {
            var hourSteps = [1, 2, 3, 4, 6, 8, 12];
            return 13 + hourSteps.indexOf(step);
        }
    }
    if (isAllWeekday && isAllMonth && hour.length == 1 && minute.length == 1) {
        step = day[1] - day[0];
        if (30 % step == 0 && day[0] <= step && day.toString() == range(day[0], 31, step).toString()) {
            var daySteps = [1, 2, 3, 5, 10, 15];
            return 20 + daySteps.indexOf(step);
        }
    }
    if (isAllWeekday && isAllMonth && day.length == 1 && hour.length == 1 && minute.length == 1) {
        return 26;
    }
    if (isAllDay && isAllMonth && weekday.length == 1 && hour.length == 1 && minute.length == 1) {
        return 27;
    }
    return 0;
}

function initEditCron() {
    var randomMinute = rand(11) * 5 + 1 + rand(3);
    var randomHour = rand(23);
    var randomDay = 1 + rand(27);
    var randomWeekday = rand(6) + 1;
    allMinute = range(0, 59);
    allHour = range(0, 23);
    allDay = range(1, 31);
    allMonth = range(1, 12);
    allWeekday = range(1, 7);
    secondZero = [0];
    allIntervals = [
        [$('#minute').val(), $('#hour').val(), $('#day').val(), $('#month').val(), $('#weekday').val(), $('#second').val(), '当前设置'],
        [allMinute, allHour, allDay, allMonth, allWeekday, [0, 30], '每隔三十秒'],
        [allMinute, allHour, allDay, allMonth, allWeekday, secondZero, '每分钟'],
        [range(rand(1), 59, 2), allHour, allDay, allMonth, allWeekday, secondZero, '每隔两分钟'],
        [range(rand(2), 59, 3), allHour, allDay, allMonth, allWeekday, secondZero, '每隔三分钟'],
        [range(rand(3), 59, 4), allHour, allDay, allMonth, allWeekday, secondZero, '每隔四分钟'],
        [range(rand(4), 59, 5), allHour, allDay, allMonth, allWeekday, secondZero, '每隔五分钟'],
        [range(rand(5), 59, 6), allHour, allDay, allMonth, allWeekday, secondZero, '每隔六分钟'],
        [range(rand(9), 59, 10), allHour, allDay, allMonth, allWeekday, secondZero, '每隔十分钟'],
        [range(rand(11), 59, 12), allHour, allDay, allMonth, allWeekday, secondZero, '每隔十二分钟'],
        [range(rand(14), 59, 15), allHour, allDay, allMonth, allWeekday, secondZero, '每隔十五分钟'],
        [range(rand(19), 59, 20), allHour, allDay, allMonth, allWeekday, secondZero, '每隔二十分钟'],
        [range(rand(29), 59, 30), allHour, allDay, allMonth, allWeekday, secondZero, '每隔三十分钟'],
        [
            [randomMinute], allHour, allDay, allMonth, allWeekday, secondZero, '每隔一小时'
        ],
        [
            [randomMinute], range(rand(1), 23, 2), allDay, allMonth, allWeekday, secondZero, '每隔两小时'
        ],
        [
            [randomMinute], range(rand(2), 23, 3), allDay, allMonth, allWeekday, secondZero, '每隔三小时'
        ],
        [
            [randomMinute], range(rand(3), 23, 4), allDay, allMonth, allWeekday, secondZero, '每隔四小时'
        ],
        [
            [randomMinute], range(rand(5), 23, 6), allDay, allMonth, allWeekday, secondZero, '每隔六小时'
        ],
        [
            [randomMinute], range(rand(7), 23, 8), allDay, allMonth, allWeekday, secondZero, '每隔八小时'
        ],
        [
            [randomMinute], range(rand(11), 23, 12), allDay, allMonth, allWeekday, secondZero, '每隔十二小时'
        ],
        [
            [randomMinute],
            [randomHour], allDay, allMonth, allWeekday, secondZero, '每天'
        ],
        [
            [randomMinute],
            [randomHour], range(rand(1) + 1, 31, 2), allMonth, allWeekday, secondZero, '每两天'
        ],
        [
            [randomMinute],
            [randomHour], range(rand(2) + 1, 31, 3), allMonth, allWeekday, secondZero, '每三天'
        ],
        [
            [randomMinute],
            [randomHour], range(rand(4) + 1, 31, 5), allMonth, allWeekday, secondZero, '每五天'
        ],
        [
            [randomMinute],
            [randomHour], range(rand(9) + 1, 31, 10), allMonth, allWeekday, secondZero, '每十天'
        ],
        [
            [randomMinute],
            [randomHour], range(rand(14) + 1, 31, 15), allMonth, allWeekday, secondZero, '每十五天'
        ],
        [
            [randomMinute],
            [randomHour],
            [randomDay], allMonth, allWeekday, secondZero, '每个月'
        ],
        [
            [randomMinute],
            [randomHour], allDay, allMonth, [randomWeekday], secondZero, '每周'
        ]
    ];
    var currentInterval = 1;
    $('<div>').append('<select id="timeIntervals" class="input-xlarge"></select>').append($('<a>', {
        href: 'javascript:;',
        title: 'Detailed time settings',
        id: 'timeDetails',
        'class': 'btn btn-info'
    }).html('<i class="icon-chevron-down icon-white" id="timeDetailsIcon"></i> 高级设置')).insertBefore('#timeSettings');
    $.each(allIntervals, function(id, interval) {
        $('#timeIntervals').append($('<option>', {
            value: id
        }).text(interval[6]));
    });
    currentInterval = timeToInterval($('#minute').val(), $('#hour').val(), $('#day').val(), $('#month').val(), $('#weekday').val(), $('#second').val());
    $('#timeIntervals').val(currentInterval);
    $('#timeSettings').hide();
    $('#timeSettings tr:first').after($('<tr>').append('<td><label for="randomMinute"><input type="checkbox" name="minute[]" id="randomMinute" value="random" /> 随机</label></td>').append('<td><label for="randomHour"><input type="checkbox" name="hour[]" id="randomHour"  value="random" /> 随机</label></td>').append('<td><label for="lastDay"><input type="checkbox" name="day[]" id="lastDay"  value="L" /> 最后一天</label></td>').append('<td>&nbsp;</td>').append('<td>&nbsp;</td>').append('<td>&nbsp;</td>'));
    $('#timeSettings').append('<tr><td colspan="6" id="quickSelect">' + ' <a class="btn" id="quickSelectButton"><i class="icon-check"></i> 快速插入 </a>' + ' <div class="input-prepend"><span class="add-on">每</span> <input type="text" value="1" id="quickSelectInterval"></div>' + ' <select id="quickSelectField"><option value="minute">分钟</option><option value="hour">小时</option><option value="day">天</option><option value="month">月</option><option value="weekday">周</option></select>' + ' <div class="input-prepend"><span class="add-on">从</span> <input type="text" value="0" id="quickSelectFrom"></div>' + ' <div class="input-prepend"><span class="add-on">到</span> <input type="text" value="59" id="quickSelectTo"></div>' + ' </td></tr>');
    $('#quickSelectField').change(function() {
        var field = '#' + $('#quickSelectField').val();
        var fromLimit = parseInt($(field + ' option:first').val());
        var toLimit = parseInt($(field + ' option:last').val());
        $('#quickSelectInterval').val(1);
        $('#quickSelectFrom').val(fromLimit);
        $('#quickSelectTo').val(toLimit);
    });
    $('#quickSelectButton').click(function() {
        var field = '#' + $('#quickSelectField').val();
        var fromLimit = parseInt($(field + ' option:first').val());
        var toLimit = parseInt($(field + ' option:last').val());
        var from = parseInt($('#quickSelectFrom').val());
        if (from < fromLimit) {
            from = fromLimit;
        }
        $('#quickSelectFrom').val(from);
        var to = parseInt($('#quickSelectTo').val());
        if (to > toLimit) {
            to = toLimit;
        }
        $('#quickSelectTo').val(to);
        var interval = parseInt($('#quickSelectInterval').val());
        if (interval < 1 || interval > toLimit) {
            interval = 1;
        }
        $('#quickSelectInterval').val(interval);
        $(field).val(range(from, to, interval));
        return false;
    });
    $('#randomMinute').prop('checked', $('#minute option:first').is(':selected'));
    $('#randomHour').prop('checked', $('#hour option:first').is(':selected'));
    $('#lastDay').prop('checked', $('#day option:first').is(':selected'));
    $('#minute option:first, #hour option:first, #day option:first').remove();
    $('#timeIntervals').change(function() {
        if (this.value == -1)
            return;
        var interval = allIntervals[this.value];
        $('#minute').val(interval[0]);
        $('#hour').val(interval[1]);
        $('#day').val(interval[2]);
        $('#month').val(interval[3]);
        $('#weekday').val(interval[4]);
        $('#second').val(interval[5]);
        $('#timeSettings select').prop('disabled', false);
        $('#timeSettings input[type="checkbox"]').prop('checked', 0);
    });
    $('#randomMinute').change(function() {
        $('#minute').prop('disabled', this.checked);
    });
    $('#randomHour').change(function() {
        $('#hour').prop('disabled', this.checked);
    });
    $('#lastDay').change(function() {
        $('#day').prop('disabled', this.checked);
    });
    $('#minute').prop('disabled', $('#randomMinute').prop('checked'));
    $('#hour').prop('disabled', $('#randomHour').prop('checked'));
    $('#day').prop('disabled', $('#lastDay').prop('checked'));
    $('#timeDetails').click(function() {
        $('#timeDetailsIcon').attr('class', $('#timeSettings').is(':visible') ? 'icon-chevron-down' : 'icon-chevron-up').addClass('icon-white');
        $('#timeSettings').toggle('slow');
    });
    $('<div class="control-group"><div class="controls"><a href="javascript:;" id="advancedToggle" class="btn btn-mini" title="Advanced settings"><i class="icon-cog"></i> <span id="advancedToggleText">More options</span></a> <span class="small">(timezone, notification, group, POST data)</span></div></div></div>').insertBefore($('#advancedSettings'));
    if (!$('#advancedSettings .control-group.error').length) {
        $('#advancedSettings').hide();
    }
    $('#advancedToggle').click(function() {
        $('#advancedToggleText').text($('#advancedSettings').is(':visible') ? 'More options' : 'Less options');
        $('#advancedSettings').toggle('slow');
    });
    if ($('#notify').val() != 1) {
        $('#cgroup-notifyEvery').hide();
    }
    $('#notify').change(function() {
        if ($(this).val() == 1) {
            $('#cgroup-notifyEvery').show('slow');
        } else {
            $('#cgroup-notifyEvery').hide('slow');
        }
    });
    if (['POST', 'PUT'].indexOf($('#httpMethod').val()) === -1) {
        $('#cgroup-postData').hide();
    }
    $('#httpMethod').change(function() {
        if (['POST', 'PUT'].indexOf($('#httpMethod').val()) === -1) {
            $('#cgroup-postData').hide('slow');
        } else {
            $('#cgroup-postData').show('slow');
        }
    });
}

function initEditCronBatch() {
    initEditCron();
    $.each(['pattern', 'expression', 'server'], function(k, field) {
        $('#cgroup-' + field).hide();
        $('#' + field + 'Enable').change(function() {
            if (this.checked) {
                $('#cgroup-' + field).show();
            } else {
                $('#cgroup-' + field).hide();
            }
        });
    });
    $('#cgroup-timeEnable').hide();
    $('#timeIntervals option:first').text("Do not change");
    $('#timeIntervals').val(0).change(function() {
        $('#timeEnable').attr('checked', $('#timeIntervals option:selected').index() !== 0);
    });
}

function initLogs() {
    $('tr:has(pre)').hide();
    $('tr:nth-child(even)').click(function() {
        $(this).next().toggle();
    });
    $('#refreshButton').click(function() {
        $(this).html('<i class="icon-refresh icon-spin"></i> Loading...');
        $('#contentText').load(this.href);
        return false;
    });
    $('#backButton').click(function() {
        $('#contentText').load(this.href);
        return false;
    });
    touchScroll('.pre-scrollable');
    // initTooltip();
}